package com.yykt.myapp.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yykt.myapp.config.GlobalUser;
import com.yykt.myapp.enums.ResultEnum;
import com.yykt.myapp.util.JsonResult;
import com.yykt.myapp.vo.ApiUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

@Component
@Slf4j
public class Appinterceptor implements HandlerInterceptor {

    ObjectMapper objectMapper;
    private GlobalUser globalUser;

    @Autowired
    public Appinterceptor(ObjectMapper objectMapper, GlobalUser globalUser) {
        this.objectMapper = objectMapper;
        this.globalUser = globalUser;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        response.setContentType("application/json;charset=UTF-8");

        // 1. 获取输入 request 获取 ak
        String requestBody = getRequestBody(request);
        log.info("handle requestBody:{}", requestBody);

        ApiUser apiUser = objectMapper.readValue(requestBody, ApiUser.class);
        String ak = apiUser.getAk();
        String sk = apiUser.getSk();
        log.info("ak:{}, sk:{}", ak, sk);
        // 2. 校验, controller
        if(!sk.equals(globalUser.getGlobalMap().get(ak))) {
            log.error("handle: ak or sk is error");

            JsonResult res = JsonResult.error(ResultEnum.USERNAME_PASSWORD_ERROR);
            String ret = objectMapper.writeValueAsString(res);
            response.getWriter().write(ret);

            return false;
        }
        // 3. 通过放行，不通过拒绝
        return true;
    }

    private String getRequestBody(HttpServletRequest request) throws IOException {
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = request.getReader();

        char[] buffer = new char[1024];
        int byteRead;
        while ((byteRead = reader.read(buffer)) != -1) {
            sb.append(buffer, 0, byteRead);
        }
        return sb.toString();
    }
}
